﻿using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using OnlineEducation.Data;
using OnlineEducation.ExternalService;
using OnlineEducation.Helpers;
using OnlineEducation.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;

namespace OnlineEducation.Services
{
    internal class TaskHostedService : IHostedService, IDisposable
    {
        private static object lockObj = new object();//定义锁

        private readonly IServiceScopeFactory scopeFactory;

        private readonly ILogger _logger;
        private ApplicationDbContext _context;
        private Timer _timer;
        private readonly IWebHostEnvironment _hostingEnv;
 
        public TaskHostedService(IServiceScopeFactory scopeFactory,
            ILogger<TaskHostedService> logger,
            IWebHostEnvironment hostingEnv)
        {
            this.scopeFactory = scopeFactory;

            _logger = logger;

            _hostingEnv = hostingEnv;
        }

        public Task StartAsync(CancellationToken cancellationToken)
        {
            _logger.LogInformation("Background Service xxx is starting.");

            _timer = new Timer(DoWork, null, TimeSpan.Zero, TimeSpan.FromMinutes(5));

            return Task.CompletedTask;
        }

        private void DoWork(object state)
        {
            _logger.LogInformation(string.Format("[{0:yyyy-MM-dd hh:mm:ss}]Background Service xxx is working.", DateTime.Now));

            lock (lockObj)
            {
                using (var scope = scopeFactory.CreateScope())
                {
                    _context = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();

                    #region //process tasks
                    try
                    {
                      

                    }
                    catch (Exception ex)
                    {
                        _logger.LogError(ex.Message, ex.ToString());

                    }
                    #endregion

                }
            }
        }

        public Task StopAsync(CancellationToken cancellationToken)
        {
            _logger.LogInformation("Background Service xxx is stopping.");

            _timer?.Change(Timeout.Infinite, 0);

            return Task.CompletedTask;
        }

        public void Dispose()
        {
            _timer?.Dispose();
        }
    }



}
